from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.views import View
from django.core.paginator import Paginator

from apps.goods.models import GoodsChannel
from apps.goods.utils import get_breadcrumb
from apps.goods.models import SKU
from apps.contents.utils import get_categories
from apps.goods.models import GoodsCategory
from utils.response_code import RETCODE


# 3, 商品详情页：
class DetailView(View):
    def get(self, request, sku_id):
        # 获取当前sku的信息
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return render(request, '404.html')

        # 查询商品频道分类
        categories = get_categories(request)
        # 查询面包屑导航
        breadcrumb = get_breadcrumb(sku.category)

        # 构建当前商品的规格键
        sku_specs = sku.specs.order_by('spec_id')
        sku_key = []
        for spec in sku_specs:
            sku_key.append(spec.option.id)
        # 获取当前商品的所有SKU
        skus = sku.spu.sku_set.all()
        # 构建不同规格参数（选项）的sku字典
        spec_sku_map = {}
        for s in skus:
            # 获取sku的规格参数
            s_specs = s.specs.order_by('spec_id')
            # 用于形成规格参数-sku字典的键
            key = []
            for spec in s_specs:
                key.append(spec.option.id)
            # 向规格参数-sku字典添加记录
            spec_sku_map[tuple(key)] = s.id
        # 获取当前商品的规格信息
        goods_specs = sku.spu.specs.order_by('id')
        # 若当前sku的规格信息不完整，则不再继续
        if len(sku_key) < len(goods_specs):
            return
        for index, spec in enumerate(goods_specs):
            # 复制当前sku的规格键
            key = sku_key[:]
            # 该规格的选项
            spec_options = spec.options.all()
            for option in spec_options:
                # 在规格参数sku字典中查找符合当前规格的sku
                key[index] = option.id
                option.sku_id = spec_sku_map.get(tuple(key))
            spec.spec_options = spec_options

        # 渲染页面
        context = {
            'categories':categories,
            'breadcrumb':breadcrumb,
            'sku':sku,
            'specs': goods_specs,
        }
        return render(request, 'detail.html', context)

# 2, 商品热销
class HotView(View):
    def get(self, request, category_id):
        # 通过category_id（商品分类）获取商品, 已上架，并且按照销量分类，取前两个
        skus = SKU.objects.filter(category_id=category_id, is_launched=True).order_by("-sales")[:2]

        # 获取热销商品列表
        hot_skus = []
        for sku in skus:
            hot_skus.append({
                'id': sku.id,
                'default_image_url': sku.default_image.url,
                'name': sku.name,
                'price': sku.price
            })

        return JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'hot_skus': hot_skus})


# 1, 商品列表展示
class ListView(View):
    def get(self, request, category_id, page_num):
        # 获取三级分类的对象
        category = GoodsCategory.objects.get(id=category_id)

        # 1, 获取商品分类，调用封装的获取商品分类的方法
        categories = get_categories(request)

        # 2, 获取面包屑分类
        breadcrumb = get_breadcrumb(category)

        # 3, 获取分页和排序
        # 3.1 获取前段传递过来的排序字段
        sort = request.GET.get("sort", "default")

        # 3.2 判断排序字段
        if sort == "price":
            sort_field = "price"
        elif sort =="hot":
            sort_field = "-sales"
        else:
            sort_field = "create_time"

        # 3.4 根据排序字段查找数据库中的数据, 这里的is_launched字段表示的是是否上架
        skus = SKU.objects.filter(category=category, is_launched=True).order_by(sort_field)

        # 4 分页
        # 4.1 实例化分页的对象,参数一是分页的总数据，参数二是每一页分多少数据
        paginator = Paginator(skus, 5)

        # 4.2 查看当前显示的页
        page_skus = paginator.page(page_num)

        # 4.3 查看所有的页
        total_page = paginator.num_pages

        context = {
            'categories': categories,   # 频道分类
            'breadcrumb': breadcrumb,   # 面包屑导航
            'sort': sort,               # 排序字段
            'category': category,       # 第三级分类
            'page_skus': page_skus,     # 分页后数据
            'total_page': total_page,   # 总页数
            'page_num': page_num,       # 当前页码
        }

        return render(request, "list.html", context)

